package com.cz.batch;

import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.common.message.Message;

import java.util.ArrayList;
import java.util.List;

public class BatchProducer {
    public static void main(String[] args) throws Exception {

        DefaultMQProducer producer = new DefaultMQProducer("pg");
        producer.setNamesrvAddr("master:9876");
        // 指定要发送的消息的最大大小，默认4M
        producer.setMaxMessageSize(4 * 1024 * 1024);
        producer.start();


        // 定义要发送的消息集合
        List<Message> messages = new ArrayList<>();
        for (int i = 0; i < 100; i++) {
            byte[] body = ("Hi, " + i).getBytes();
            Message message = new Message("someTopic", "someTag", body);
            messages.add(message);
        }

        // 将消息列表分割为多个不超过4M大小的小列表
        MessageListSplitter splitter = new MessageListSplitter(messages);
        while (splitter.hasNext()) {
            try {
                List<Message> next = splitter.next();
                producer.send(next);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        producer.shutdown();


    }
}
